#include "ZigbeeGWProtocol.h"

ZigbeeGWProtocol::ZigbeeGWProtocol(QObject *parent) :
    BaseProtocol(parent)
{
    this->m_protocolType = ProtocolType::ZigbeeGWProtocol;
}

QList<Package> ZigbeeGWProtocol::parseData(QByteArray data)
{
    quint8  checkSteps = CHECK_HEAD;          //当前解析状态
    quint16 lengthCount;                 //数据长度计算
    quint8  getbodylength=0;
    quint16 bodyLength;
    quint16 checkdata=0;
    QByteArray dataArray;
    QList<Package> packageList;

    for(int i=0; i<data.size(); i++)
    {
        quint8 byte = data.at(i);
        switch(checkSteps)
        {
        case CHECK_HEAD:
            if(byte==0x68)
            {
                lengthCount=0;
                bodyLength=0;
                checkdata=0;
                getbodylength=0;
                dataArray.clear();
                checkdata+=byte;
                checkSteps=CHECK_VERSION;
            }
            break;
        case CHECK_VERSION:
            {
                checkdata+=byte;
                checkSteps=CHECK_SEQ;
            }
            break;
        case CHECK_SEQ:
            {
              checkdata+=byte;
              checkSteps=CHECK_Type;
            }
            break;
        case CHECK_Type:
            {
               checkdata+=byte;
               checkSteps=CHECK_LENGTH;
            }
            break;
        case CHECK_LENGTH:
            {
                checkdata+=byte;
                if(lengthCount==0)
                {
                  bodyLength+=byte;
                  lengthCount++;
                }
                else if(lengthCount==1)
                {
                    bodyLength=bodyLength<<8|byte;
                    checkSteps=CHECK_BODY;
                }
                break;
            }
         case CHECK_BODY:
                checkdata+=byte;
                dataArray.append(byte);
                getbodylength++;
                if(getbodylength==bodyLength)
                {
                    checkSteps=CHECK_CHECKCODE;
                }
                break;
         case CHECK_CHECKCODE:
                if((checkdata&0xff)==byte)
            {
                Package package;
           //     package.setHead(dataArray.mid(0,1));
                package.setVersion(0x01);
                package.setFunction(dataArray.mid(0,2).toHex().toInt(0,16));
                package.setLength(bodyLength);
                package.setBody(dataArray);
                package.setCheckCode(byte);
                packageList.append(package);
            }
            checkSteps=CHECK_HEAD;
            break;
        }
    }
    return packageList;
}


QByteArray ZigbeeGWProtocol::generateData(Package package)
{
    QByteArray head = QByteArray::fromHex(QString("A5AA5A").toLatin1());
    QByteArray data;
    data.append(head);
    data.append(DataTypeConver::intToByteArray(package.function(),1));
    data.append(package.body());
    return data;
}
